package com.cnr.util;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.cnr.model.Credentials;

public class ManageCredentials {

	private static final Logger logger = Logger.getLogger(ManageCredentials.class);

	public Credentials getUser(String username, String password) {
		Session session = HibernateUtil.getSession();
		Credentials user = null;
		try {
			user = (Credentials) session
					.createCriteria(Credentials.class)
					.add(Restrictions.and(
							Restrictions.eq("username", username),
							Restrictions.eq("password", password)))
					.uniqueResult();
		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return user;
	}
	
	public Long addCredentials(String username, String password, String email, String role) {
		Session session = HibernateUtil.getSession();
		Long userId = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Credentials user = new Credentials();
			user.setUsername(username);
			user.setPassword(password);
			user.setEmail(email);
			user.setRole(role);
			userId = (Long) session.save(user);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return userId;
	}

}
